package com.kude.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.kude.entity.Article;
import com.kude.entity.ArticleCategory;
import com.kude.entity.ArticleCategoryPrefix;
import com.kude.entity.Product;
import com.kude.manager.OperException;
import com.kude.service.ArticleCategoryPrefixService;
import com.kude.service.ArticleCategoryService;
import com.kude.service.ArticleService;
import com.kude.util.BeanFactory;

public class GetArticleServlet extends HttpServlet {
	public ArticleService articleService;
	public ArticleCategoryService articleCategoryService;
	public ArticleCategoryPrefixService articleCategoryPrefixService;

	/**
	 * Constructor of the object.
	 */
	public GetArticleServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		articleService = BeanFactory.getBean(ArticleService.class.getName());
		articleCategoryService = BeanFactory
				.getBean(ArticleCategoryService.class.getName());
		articleCategoryPrefixService = BeanFactory
				.getBean(ArticleCategoryPrefixService.class.getName());
		String operation = request.getParameter("operation");
		if (operation.equals("add")) {
			try {
				this.add(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("update")) {
			try {
				this.update(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("delete")) {
			try {
				this.delete(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleByIsDisplayOnHomepage")) {
			try {
				this.getArticleByIsDisplayOnHomePage(request, response);
			} catch (Exception e) {
				//
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleByImageURLNullOrNot")) {
			try {
				this.getArticleByImageURLNullOrNot(request, response);
			} catch (Exception e) {
				//
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleListByCategoryId")) {
			try {
				this.getArticleListByCategoryId(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleByTopParentCategory")) {
			try {
				this.getArticleByTopParentCategoryId(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 通过顶层类别ID获得所属所有文章 ，如点击教育培训
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void getArticleByTopParentCategoryId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		ArticleCategoryPrefix articleCategoryPrefix = articleCategoryPrefixService.getArticleCategoryPrefix(categoryId);
		List<ArticleCategory> articleCategoryList = (ArrayList<ArticleCategory>) articleCategoryService
				.getArticleCategoryListByPrefix(articleCategoryPrefix
						.getPrefix());
		System.out.println(articleCategoryList.size()+"!!!!!!!!!!!!!!");
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articles") || name.equals("articleCategoryPrefix")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		
		JSONArray productByTopCategoryIdList = JSONArray
				.fromObject(articleService.getArticleListByCategoryIdList(
						start, limit, articleCategoryList),config);
		
        List<Integer> categoryIds = new ArrayList<Integer>();
        for(int i = 0; i < articleCategoryList.size(); i++){
        	categoryIds.add(articleCategoryList.get(i).getArticleCategoryId());
        }
        int total = articleService.getTotalByCategoryIdList(categoryIds);
        System.out.println("total:" + total);
        StringBuilder result = new StringBuilder();
        result.append("{\"total\":" + total + ",\"rows\":");
		result.append(productByTopCategoryIdList.toString());
		result.append("}");
		
		response.getWriter().write(result.toString());
		response.getWriter().flush();
	}
	/**
	 * 根据类别Id取得所属的所有文章
	 * 
	 * @param categoryId
	 * @param pageNow
	 * @param pageSize
	 * @throws Exception
	 */
	private void getArticleListByCategoryId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		System.out.println("Start:" + start + " limit:" + limit);
		JsonConfig config = new JsonConfig();
		
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articles") || name.equals("articleCategoryPrefix")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        
		JSONArray productByCategoryIdList = JSONArray.fromObject(articleService
				.getArticleListByCategory(start, limit, categoryId),config);
		
		List<Integer> categoryIds = new ArrayList<Integer>();
		categoryIds.add(categoryId);
		int total = articleService.getTotalByCategoryIdList(categoryIds);
		System.out.println("total:" + total);
		StringBuilder result = new StringBuilder();
		result.append("{\"total\":" + total + ",\"rows\":");
		result.append(productByCategoryIdList.toString());
		result.append("}");

		response.getWriter().write(result.toString());
		response.getWriter().flush();
	}

	private void getArticleByImageURLNullOrNot(HttpServletRequest request,
			HttpServletResponse response) throws IOException, Exception {
		int imageURLNullOrNot = Integer.parseInt(request
				.getParameter("imageURLNullOrNot"));
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articleCategory")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray productIsOnsaleList = JSONArray.fromObject(articleService
				.getArticleByImageURLNullOrNot(pageNow, pageNow),config);
		
		response.getWriter().write(productIsOnsaleList.toString());
		response.getWriter().flush();

	}

	private void getArticleByIsDisplayOnHomePage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int isDisplayOnHomePage = Integer.parseInt(request
				.getParameter("isDisplayOnHomepage"));
		System.out.println(isDisplayOnHomePage);
		int pageNow = Integer.parseInt(request.getParameter("pageNow"));
		System.out.println(pageNow);
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		System.out.println(pageSize);
		System.out.println(articleService.getArticleByIsDisplayOnHomePage(
				pageNow, pageSize, isDisplayOnHomePage).size()
				+ "```````````````");
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articleCategory")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		String articleIsDisplayOnHomePageList = JSONArray.fromObject(
				articleService.getArticleByIsDisplayOnHomePage(pageNow,
						pageSize, isDisplayOnHomePage),config).toString();
		response.getWriter().write(articleIsDisplayOnHomePageList);
		response.getWriter().flush();
	}

	private void delete(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			articleService.deleteArticle(id);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	private void update(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int id = Integer.parseInt(request.getParameter("articleId"));
		String content = request.getParameter("content");
		String source = request.getParameter("source");
		String title = request.getParameter("title");
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		ArticleCategory a = articleCategoryService.getArticleCategory(categoryId);
		
		Article article = articleService.getArticle(id);
		article.setArticleCategory(a);
		article.setContent(content);
		article.setSource(source);
		article.setTitle(title);
		try {
			
			// TODO 把需要更改的字段更新
			articleService.updateArticle(article);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	private void add(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			Article article = new Article();
			int categoryId = Integer.parseInt(request.getParameter("categoryId"));
			String content = request.getParameter("content");
			String source = request.getParameter("source");
			String title = request.getParameter("title");
			String isDisplayOnHomePage = request.getParameter("isDisplayOnHomePage");
			ArticleCategory a = articleCategoryService.getArticleCategory(categoryId);
			
			article.setArticleCategory(a);
			article.setContent(content);
			article.setSource(source);
			article.setTime(new Date());
			article.setTitle(title);
			article.setViews(1);
			if(isDisplayOnHomePage != null){
				int dis = Integer.parseInt(isDisplayOnHomePage);
				article.setIsDisplayOnHomePage(dis);
			}
			// TODO 把需要更改的字段更新
			articleService.addArticle(article);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	
}
